<template>
	<div>
		<img class="imgs" src="@/assets/images/ikun.jpg">
		<div class="logoin">
			欢迎登录
		</div>
		
	<van-cell-group>
			<van-field label="账号" placeholder="请输入账号" v-model="loginForm.uname" />
			<van-field label="密码" placeholder="请输入密码" type="password" v-model="loginForm.password"></van-field>
			<van-button @click="onClickLogin" type="primary" size="normal" block>登录</van-button>
		</van-cell-group>
		<div class="goto">
			<van-button @click="onRegister">若还没有账号？点击前往注册</van-button>
		</div>
	</div>
</template>
<script>
	import {
		getUserLocal,
		setUserLocal,
		setTokenLocal
	} from "@/utils/auth.js";
	import {
		loginAPI
	} from "@/api/user.js";
	import {
		registerAPI
	} from "@/api/user.js";
	export default {
		data() {
			return {
				loginForm: {
					uname: "dingding", //设置默认值，仅是方便调试
					password: "123456",
				},
			};
		},
		mounted() {
			//初始赋值 ，从本地存储中获取用户名
			this.loginForm.uname = getUserLocal().name;
		},
		methods: {
			//处理用户登录
			onClickLogin() {
				if (this.loginForm.uname === "" || this.loginForm.password === "") {
					this.$toast("账号或密码不能为空");
					return;
				}
				let params = this.loginForm;
				loginAPI(params).then(result => {
					this.$toast({
						message: "登录成功！",
						duration: 1000
					});
					//本地保存用户信息（id,name）保存Token 调用utils/auth.js模块功能
					setTokenLocal(result.data.token);
					setUserLocal(result.data);
					//登录成功后跳转到需要重定向的路径，默认是我的页面（user）
					let toPath = this.$route.params.redirect || "user";
					setTimeout(() => {
						this.$router.replace({
							path: toPath
						});
					}, 1000)

				});
			},
			// 处理用户注册
			onRegister() {
				//路由跳转到用户注册页面
					this.$router.push({
						name: "register",
					});
			},
		},
	};
</script>
<style lang="less" scoped>
	.goto {
		display: block;
		margin-top: 25px;
		text-align: center;
	}
	.logoin{
		text-align: center;
		font-size: 25px;
	}
	.imgs {
		display: flex;
		margin: 0 auto;
	}
</style>